import router from '@/router'
import instance from '../utils/request'
import { Message } from 'element-ui'
import qs from 'qs'

// 登入请求
function login (loginForm) {
  return instance({
    url: '/login',
    method: 'post',
    headers: { 'content-type': 'application/x-www-form-urlencoded' },
    data: qs.stringify(loginForm)
  }).then(res => {
    sessionStorage.setItem('token', res.data.token)
    sessionStorage.setItem('user', JSON.stringify(res.data.user))
    Message.success('登入成功!')
    router.push('/home').then()
  }).catch(() => {
    Message.error('用户名或密码错误')
  })
}

// 注销请求
function logout () {
  instance({
    url: '/out'
  }).then(res => {
    Message.success('注销成功!')
    sessionStorage.clear()
    router.replace('/').then()
  }).catch(() => {
    Message.error('修改失败,服务器错误!')
  })
}

// 检查验证码是否正确
async function checked (code) {
  let status
  await instance.get('/code/checkVerify/' + code).then(res => {
    status = res
  })
  return status
}

export default {

  login,
  checked,
  logout
}
